import { Engine, Color3, SceneLoader, FollowCamera, Camera, HemisphericLight, Vector3, Sprite, Scene, ArcRotateCamera, PointLight, StandardMaterial, Texture, ShaderMaterial, IAnimationKey, AssetsManager, MeshAssetTask, AbstractMesh, PickingInfo, Mesh, Animation, MeshBuilder } from 'babylonjs'
import 'babylonjs-loaders';
// @ts-ignore

// 标点
export class Image {
  private dom: HTMLCanvasElement
  private engine: Engine
  private scene: Scene
  private camera: ArcRotateCamera

  constructor(dom: HTMLCanvasElement) {
    this.dom = dom
    this.engine = new Engine(this.dom, true)  // 设置引擎
    this.scene = new Scene(this.engine)   // 创建场景

    // 纵轴旋转45°
    this.camera = new ArcRotateCamera("Camera", Math.PI / 180 * 45, Math.PI / 180 * 45, 200, Vector3.Zero(), this.scene, true); // 创建相机
    this.camera.attachControl(this.dom, false)

    // 创建半球光
    const light = new HemisphericLight('light', new Vector3(10, 5, 5), this.scene);
    const x = Mesh.CreateLines('x', [Vector3.Zero(), new Vector3(1000, 0, 0)], this.scene)
    x.color = new Color3(1, 0, 0);
    const y = Mesh.CreateLines('y', [Vector3.Zero(), new Vector3(0, 1000, 0)], this.scene)
    y.color = new Color3(0, 1, 1);
    const z = Mesh.CreateLines('z', [Vector3.Zero(), new Vector3(0, 0, 1000)], this.scene)
    z.color = new Color3(1, 0, 1);



    SceneLoader.ImportMeshAsync('m', '/', '1.stl', this.scene).then((res) => {
      const material = new StandardMaterial('new', that.scene)
      // material.diffuseColor = new Color3(255, 255, 0)
      res.meshes[0].material = material

    })

    // const box = Mesh.CreateBox('box', 20, this.scene)
    const that = this

    this.scene.onPointerDown = function (evt) {
      const pickResult = that.scene.pick(this.pointerX, this.pointerY);

      if (pickResult?.hit && pickResult.pickedMesh?.name == 'stlmesh') {
        const point = Mesh.CreateBox('point', 2, that.scene)
        const mt = new StandardMaterial('', that.scene)
        mt.diffuseColor = new Color3(1, 0, 0)
        point.material = mt;

        point.position.set(pickResult.pickedPoint!.x + 0, pickResult.pickedPoint!.y + 0, pickResult.pickedPoint!.z + 0)
      }
    };


  }
  render() {
    // 引擎渲染场景
    this.engine.runRenderLoop(() => {
      this.scene.render()
    })
  }
}


